package com.example.sunmiv1.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sunmiv1.R;
import com.example.sunmiv1.entity.GuideBean;
import com.example.sunmiv1.utils.ByteArrayTohexHepler;
import com.example.sunmiv1.utils.Converter;
import com.example.sunmiv1.utils.Tools;
import com.example.sunmiv1.utils.net.ACache;
import com.example.sunmiv1.utils.net.Common;
import com.example.sunmiv1.utils.net.GsonUtils;
import com.example.sunmiv1.utils.net.HttpUtils;
import com.example.sunmiv1.utils.net.LoadingDialog;
import com.example.sunmiv1.utils.net.TextCallBack;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.example.sunmiv1.utils.ByteArrayTohexHepler.ByteArrayToHexString;
import static com.example.sunmiv1.utils.ByteArrayTohexHepler.flipHexStr;

public class AddVipActivity extends Activity {

    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(R.id.title_title)
    TextView titleTitle;
    @BindView(R.id.et_addVip_name)
    EditText etAddVipName;
    @BindView(R.id.et_addVip_phone)
    EditText etAddVipPhone;
    @BindView(R.id.et_addVip_money)
    EditText etAddVipMoney;
    @BindView(R.id.et_addVip_pass)
    EditText etAddVipPass;
    @BindView(R.id.tv_addVip_birthday)
    TextView tvAddVipBirthday;
    @BindView(R.id.et_addVip_card)
    EditText etAddVipCard;
    @BindView(R.id.tv_addVip_save)
    TextView tvAddVipSave;
    @BindView(R.id.spinner_addVip)
    Spinner spinnerAddVip;

    private ACache aCache;
    private Context context;
    private GuideBean guideBean;
    private LoadingDialog loadingDialog;
    private int guide_index = 9999;
    private List<String> guideNameList = new ArrayList<>();
    private List<GuideBean.GuideListBean> guideList = new ArrayList<>();

    //nfc
    private NfcAdapter mNfcAdapter;
    private PendingIntent pi;
    private boolean isSupportNfc, isOpenNfc;
    private static final String TAG = "AddVipActivity";

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    guideList.clear();
                    guideNameList.clear();
                    GuideBean.GuideListBean dataBean = new GuideBean.GuideListBean();
                    dataBean.setId("0");
                    dataBean.setGuidename(getString(R.string.null1));
                    guideList.add(dataBean);
                    guideNameList.add(getString(R.string.null1));
                    for (int i = 0; i < guideBean.getGuide_list().size(); i++) {
                        guideList.add(guideBean.getGuide_list().get(i));
                        guideNameList.add(guideBean.getGuide_list().get(i).getGuidename());
                    }
                    setCateAdapter();
                    break;
                case 2:
                    guideList.clear();
                    guideNameList.clear();
                    GuideBean.GuideListBean dataBean1 = new GuideBean.GuideListBean();
                    dataBean1.setId("0");
                    dataBean1.setGuidename(getString(R.string.null1));
                    guideList.add(dataBean1);
                    guideNameList.add(getString(R.string.null1));
                    setCateAdapter();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_add_vip);
        context = this;
        ButterKnife.bind(this);
        aCache = ACache.get(context);
        loadingDialog = new LoadingDialog(context);
        titleTitle.setText(R.string.addVip);
        getGuide();
        initListener();
        //nfc
        PackageManager packageManager = this.getPackageManager();
        isSupportNfc = packageManager.hasSystemFeature(PackageManager.FEATURE_NFC);
        Log.e(TAG, "onCreate: isSupportNfc=" + isSupportNfc);
        if (isSupportNfc) {
            mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
            pi = PendingIntent.getActivity(this, 0, new Intent(this, getClass())
                    .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
            if (mNfcAdapter != null && !mNfcAdapter.isEnabled()) {
                isOpenNfc = false;
            } else {
                isOpenNfc = true;
            }
        }
    }

    private void initListener() {
        spinnerAddVip.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                guide_index = position;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mNfcAdapter != null && isSupportNfc && isOpenNfc) {
            mNfcAdapter.enableForegroundDispatch(this, pi, null, null);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        // Toast.makeText(context, "onNewIntent", Toast.LENGTH_SHORT).show();

        String ex_id;
        Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        String num1 = ByteArrayToHexString(tagFromIntent.getId());
        String num2 = flipHexStr(num1);
        Log.e(TAG, "onNewIntent: 1=" + num2);
        String num = "";
        if (num2.length() > 10) {
            try {
                num = ByteArrayTohexHepler.hex2String(num2);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            Long cardNo = Long.parseLong(num2, 16);
            Log.e(TAG, "onNewIntent: 2=" + cardNo);
            num = cardNo.toString();
        }
        if (num.length() != 10) {
            while (num.length() < 10) {
                num = "0" + num;
            }
        }
        ex_id = num;
        Log.e("==================", ex_id);
        //Toast.makeText(getApplicationContext(), num, Toast.LENGTH_SHORT).show();
        etAddVipCard.setText(ex_id);
        etAddVipCard.setSelection(ex_id.length());
    }

    private void setCateAdapter() {
        ArrayAdapter arrayAdapter = new ArrayAdapter(context, R.layout.item_select, guideNameList);
        arrayAdapter.setDropDownViewResource(R.layout.item_drop);
        spinnerAddVip.setAdapter(arrayAdapter);
    }

    @OnClick({R.id.title_back, R.id.tv_addVip_birthday, R.id.tv_addVip_save})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.tv_addVip_birthday:
                Calendar calendar = Calendar.getInstance();
                new DatePickerDialog(context, AlertDialog.THEME_HOLO_LIGHT, new DatePickerDialog.OnDateSetListener() {
                    // 綁定監聽器(How the parent is notified that the date is set.)
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        // 此處得到選擇的時間，可以進行你想要的操作
                        if ((monthOfYear + 1) < 10) {
                            tvAddVipBirthday.setText(year + "-0" + (monthOfYear + 1) + "-" + dayOfMonth);
                        } else {
                            tvAddVipBirthday.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
                        }
                    }
                }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)).show();
                break;
            case R.id.tv_addVip_save:
                if (TextUtils.isEmpty(etAddVipCard.getText().toString())) {
                    if (TextUtils.isEmpty(etAddVipName.getText().toString().trim())) {
                        Toast.makeText(context, "請輸入姓名", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (TextUtils.isEmpty(etAddVipPhone.getText().toString().trim()) ||
                            etAddVipPhone.getText().toString().trim().length() != 11) {
                        Toast.makeText(context, "請輸入正確的手機號", Toast.LENGTH_SHORT).show();
                        return;
                    }
                } else {
                    if (TextUtils.isEmpty(etAddVipPass.getText().toString().trim()) ||
                            etAddVipPass.getText().toString().trim().length() != 6) {
                        Toast.makeText(context, "請輸入密碼，必須6位", Toast.LENGTH_SHORT).show();
                        return;
                    }
                }
                AddVip();
                break;
        }
    }



    private void getGuide() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("store_id",aCache.getAsString("storeid"));
            jsonObject.put("merchant_id",aCache.getAsString("merchantid"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        HttpUtils.post(context, Common.GET_GUIDE, jsonObject, new TextCallBack() {
            @Override
            protected void onSuccess(String text) {
                guideBean = GsonUtils.JsonToBean(text, GuideBean.class);
                Message msg = new Message();
                if (guideBean.getStatus() == 1) {
                    msg.what = 1;
                } else {
                    msg.what = 2;
                }
                handler.sendMessage(msg);
            }

            @Override
            protected void onFailure(ResponseException e) {

            }
        });
    }

    private void AddVip() {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            JSONObject vip_info = new JSONObject();
            jsonObject.put("platform_type", aCache.getAsString("platform_type"));
            if (!TextUtils.isEmpty(etAddVipName.getText().toString().trim())) {
                vip_info.put("name", etAddVipName.getText().toString().trim());
            }
            if (!TextUtils.isEmpty(etAddVipPhone.getText().toString().trim())) {
                vip_info.put("mobile_phone", etAddVipPhone.getText().toString().trim());
            }
            vip_info.put("balance", 0);
            if (!TextUtils.isEmpty(etAddVipPass.getText().toString().trim())) {
                vip_info.put("password", etAddVipPass.getText().toString().trim());
            }
            if (!TextUtils.isEmpty(tvAddVipBirthday.getText().toString().trim())) {
                vip_info.put("birthday", tvAddVipBirthday.getText().toString().trim());
            }
            vip_info.put("vip_type", 1);
            if (!TextUtils.isEmpty(etAddVipCard.getText().toString())) {
                vip_info.put("card_key", etAddVipCard.getText().toString().trim());
            }
            jsonObject.put("user_type", aCache.getAsString("userType"));
            if (guide_index != 9999) {
                vip_info.put("guide_id", guideList.get(guide_index).getId());
            } else {
                vip_info.put("guide_id", 0);
            }
            jsonObject.put("vip_info", vip_info);
            jsonObject.put("use_id",aCache.getAsString("uid"));
            jsonObject = Tools.createParameterCode(jsonObject);
            HttpUtils.post(context, Common.ADD_VIP, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    loadingDialog.dismiss();
                    try {
                        JSONObject json = new JSONObject(text);
                        Toast.makeText(context, json.getString("msg"), Toast.LENGTH_SHORT).show();
                        if (json.getInt("status") == 1) {
                            etAddVipName.setText("");
                            etAddVipPhone.setText("");
                            etAddVipPass.setText("");
                            tvAddVipBirthday.setText("");
                            etAddVipCard.setText("");
                            spinnerAddVip.setSelection(0);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

}
